package tcp

import (
	log "github.com/sirupsen/logrus"
	"net"
)

type TcpServer struct {
	OnConnect func(conn net.Conn) // 链接到来
	listener  net.Listener
}

// Close 关闭服务
func (s *TcpServer) Close() {
	err := s.listener.Close()
	if err != nil {
		log.Warning("TcpServer Close error!! -->", err)
	}
}

// Listener 服务开启
func (s *TcpServer) Listener(network, addr string) (err error) {
	if s.listener, err = net.Listen(network, addr); err != nil {
		return err
	}

	for {
		conn, err := s.listener.Accept()
		if err != nil {
			return err
		}
		go s.OnConnect(conn)
	}
}
